package com.elitel.frame.base.component;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;


/**
 * 开启springcache缓存服务
 */
//@EnableCaching
//@Configuration
public class CacheConfig {


    public static final String DEFAULT = "DEFAULT";
    public static final String TIMEOUT_5_MINUTE = "TIMEOUT_5_MINUTE";
    public static final String TIMEOUT_10_MINUTE = "TIMEOUT_10_MINUTE";
    public static final String TIMEOUT_30_MINUTE = "TIMEOUT_30_MINUTE";
    public static final String TIMEOUT_60_MINUTE = "TIMEOUT_60_MINUTE";
    public static final String TIMEOUT_120_MINUTE = "TIMEOUT_120_MINUTE";
    public static final String TIMEOUT_300_MINUTE = "TIMEOUT_300_MINUTE";

/**
     * spring cache 注解相关序列化操作
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        GenericJackson2JsonRedisSerializer gen = new GenericJackson2JsonRedisSerializer();
        StringRedisSerializer srs = new StringRedisSerializer();
        // 配置序列化
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        RedisCacheConfiguration redisCacheConfiguration = config
                // 键序列化方式 redis字符串序列化
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(srs))
                // 值序列化方式 简单json序列化
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(gen));
        return RedisCacheManager.builder(factory).cacheDefaults(redisCacheConfiguration).build();

    }


}
